<!--
 * @Author: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @Date: 2025-05-24 16:46:14
 * @LastEditors: wb_wangjiudeng wb_wangjiudeng@tcl.com
 * @LastEditTime: 2025-05-25 13:56:37
 * @FilePath: \iam-ui\iam-ui\src\components\echarts\lineBar.vue
 * @Description: 文件介绍
 * 
 * Copyright (c) 2025 by user.email, All Rights Reserved. 
-->
<template>
  <div class="chart" ref="chartRef"></div>
</template>

<script setup>
import { ref, defineProps, watch, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";

const chartRef = ref(null);
let chartInstance = null;

const props = defineProps({
  color: {
    type: Array,
    default: () => [
      "#2396eb",
      "#4ecb73",
      "#fbd437",
      "#f04864",
      "#975fe5",
      "#36cbcb",
      "#f759ab",
    ],
  },
  direction: {
    type: Boolean,
    default: false,
  },
  legend: {
    type: Boolean,
    default: false,
  },
  xAxisData: {
    type: Array,
    default: () => [],
  },
  seriesData: {
    type: Array,
    default: () => [],
  },
});

function enhanceLineWidth(series) {
  return series.map((item) => {
    if (item.type === "line") {
      return {
        ...item,
        lineStyle: { ...(item.lineStyle || {}), width: 4 },
      };
    }
    return item;
  });
}

function getBaseOption() {
  return {
    color: props.color,
    tooltip: {
      trigger: "axis",
    },
    legend: props.legend
      ? {
          top: 10,
        }
      : null,
    grid: {
      left: "3%",
      right: "4%",
      bottom: 0,
      top: 10,
      containLabel: true,
    },
    xAxis: props.direction
      ? { type: "value" }
      : {
          type: "category",
          data: props.xAxisData,
        },
    yAxis: props.direction
      ? {
          type: "category",
          data: props.xAxisData,
        }
      : {
          type: "value",
        },
    series: enhanceLineWidth(props.seriesData),
  };
}
// 初始化
const initChart = () => {
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  chartInstance.setOption(getBaseOption(), true);
};

// 监听 xAxisData 和 seriesData 变化，自动更新 option
watch(
  () => [props.xAxisData, props.seriesData],
  () => {
    updateOption();
  },
  { deep: true }
);

function updateOption() {
  if (chartInstance) {
    chartInstance.setOption(getBaseOption(), true);
  }
}

onMounted(() => {
  initChart();
  window.addEventListener("resize", resizeChart);
});

onBeforeUnmount(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
  window.removeEventListener("resize", resizeChart);
});

function resizeChart() {
  if (chartInstance) {
    chartInstance.resize();
  }
}
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
